import Vue from "vue"
import VueRouter from "vue-router"
import routes from './routers'
import store from '@/store/index'
Vue.use(VueRouter);
//引入并使用路由插件

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace

//重写push|replase方法
VueRouter.prototype.push = function(loaction,resolve,reject){
    if(resolve && reject){//注意这里要改变this指向 不然push没办法找到路由
        originPush.call(this,loaction,resolve,reject)
    }else{
        originPush.call(this,loaction,(name)=>{},(name)=>{})
    }
}

//重写push|replase方法
VueRouter.prototype.replace = function(loaction,resolve,reject){
    if(resolve && reject){//注意这里要改变this指向 不然push没办法找到路由
        originReplace.call(this,loaction,resolve,reject)
    }else{
        originReplace.call(this,loaction,()=>{},()=>{})
    }
}


const router = new VueRouter({
    routes,
    scrollBehavior(to,from,savedPostation) {//设置滚动条事件 跳转之后滚动条在最上方
        return {x : 0, y: 0}
    }
});
router.beforeEach(async(to,from,next)=>{
    if(store.state.register.haveonline&&(to.path === '/login'||to.path === '/refister')){
        alert('请先退出登录')
        return
    }
    if(localStorage.getItem('token')){
        try {
            await store.dispatch('register/haveUserData')
        } catch (error) {
            alert('身份信息失效请重新登录')
            localStorage.removeItem('token')
            next('/login')
        }   
    }else{
        if(to.path === '/center' || to.path === "/center/myorder" || to.path === "/center/groupOrder"|| to.path === '/pay' ||to.path === '/settlement' ||to.path === '/trade'){
            alert('请先登录')
            console.log(from.path)
            next(`/login?msg=${from.path}`)
            return
        }
    }
    console.log(to)
    next()
})
router.afterEach((to)=>{
    if(to.meta.title){
        document.title = to.meta.title
    }else{
        document.title = to.params.keyword || to.query.categoryName || "搜索"
    }
})
export default router